package top.codedance.iotp.common.util.IEEE754;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * IEEE754 convert tool (32bit)
 */
public class IEEE754Util {

    /**
     * IEEE754标准（四字节转浮点数）,公式转换
     * @param hex
     * @return
     */
    public static float hex2FloatIeee(byte[] hex){
        String hexStr = DataTransform.bytesToHex(hex);
        StringBuilder binaryStr = new StringBuilder();
        for(int i=0;i< hexStr.length();i+=2){
            String a = hexStr.substring(i,i+2);
            int c = Integer.parseInt(a,16);
            String item = String.format("%08d",Integer.parseInt(Integer.toBinaryString(c)));
            binaryStr.append(item);
        }
        int n =  Integer.parseInt(binaryStr.substring(1,9),2);
        String mStr = binaryStr.substring(9,binaryStr.length()-1);
        double sum = 0;
        for(int i =1;i<=mStr.length();i++){
            if(mStr.charAt(i-1)=='1'){
                sum = sum+Math.pow(0.5,i);
            }
        }
        float v = (float) ((Math.pow(2, n - 127)) * (1 + sum));
        return v;
    }

    /**
     * IEEE754标准（四字节转浮点数）调用JDK接口转换
     * @param bytes
     * @param reverse
     * @return
     */
    public static float hex2float(byte[] bytes, boolean reverse){
        float result;
        if(reverse){
            //bytes = DataTransform.bytesArrayReverse(bytes);
            result = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).getFloat();
        }

        /****************************此方式数据太大会超出int类型范围****************************/
        //String hex= DataTransform.encodeHexStr(bytes, true);
        //return Float.intBitsToFloat(Integer.valueOf(hex, 16));
        /****************************此方式数据太大会超出int类型范围****************************/

        result = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();

        return result;
    }

    /**
     * IEEE754标准（浮点数转四字节）调用JDK接口转换
     * @param f
     * @return
     */
    public static byte[] float2hex(float f){
        int intBits = Float.floatToRawIntBits(f);
        return DataTransform.intToByteArray(intBits);
    }

    /**
     * 调用示例
     * @param args
     */
    public static void main(String[] args){
        //把字节数据转成float
        byte[] bytes = {(byte) 0x7B, (byte) 0x20, (byte) 0xB1, (byte) 0x2C};
        float result = IEEE754Util.hex2float(bytes, true);
        System.out.println(result);

        //把float转成字节数组
        float f = 5.0342486E-12f;
        byte[] result2 = IEEE754Util.float2hex(f);
        System.out.println(DataTransform.bytesToHex(result2));
    }
}
